#!/EasyReport/Python/bin
# -*- coding: utf-8 -*-

# @Time       : 2021/08/27 10:00
# @Author     : 何彦龙10181500
# @Email      : 10181500@zte.com.cn
# @File       : EncryptUtil.py

from Crypto.Cipher import AES
import hashlib

# 提示ModuleNotFoundError:No module named ‘Crypto.Cipher解决方案：
# pip uninstall Crypto
# pip uninstall pycrypto
# pip install pycryptodome

class EncryptUtil():

    def encAES(self, s):
        """
        加密
        """
        h = self.pbkdf2("easy", "report")
        key, iv = h[:16], h[4:20]
        b = self.s2b(s)  #填充
        BS = 16  #AES.block_size=16字节
        pad = BS - len(b) % BS
        b += bytes([pad]) * pad
        cryptor = AES.new(key, AES.MODE_CBC, iv)  #加密
        return self.b2h(cryptor.encrypt(b))

    def decAES(self, hexstr):
        """
        解密
        """
        h = self.pbkdf2("easy", "report")
        key, iv = h[:16], h[4:20]
        b = self.h2b(hexstr)  #解密
        cryptor = AES.new(key, AES.MODE_CBC, iv)
        b = cryptor.decrypt(b)
        b = b[0:-b[-1]]  #去填充
        return self.b2s(b)

    def pbkdf2(self, s, salt):
        """
        hash，返回的长度跟对应的sha保持一致,返回20字节。
        """
        return hashlib.pbkdf2_hmac('sha1', self.s2b(s), self.s2b(salt), 10000)

    def b2h(self, bins):
        """
        转换byte为hex
        """
        return ''.join(["%02X" % x for x in bins]).strip()

    def h2b(self, hexStr):
        """
        转换hex为byte
        """
        return bytes.fromhex(hexStr)

    def s2b(self, s):
        """
        转换str为byte
        """
        return s.encode()

    def b2s(self, b):
        """
        转换byte为str
        """
        return b.decode()

def encstr(s):
    """
    加密
    """
    return EncryptUtil().encAES(s)


def decstr(hexstr):
    """
    解密
    """
    return EncryptUtil().decAES(hexstr)

util= EncryptUtil()
print(util.encAES("E:\DataSet\IRAHO\DataSet\VoNR.db"))
# util.encAES("GBASE")
# print(util.encAES("NAN"))
# print(util.decAES('CBCB8E09FC05EA030CFF54733F375620'))